package com.atguigu.mapreduce.source;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public abstract class GeneralSource {
    private static final Logger LOG = LoggerFactory.getLogger(GeneralSource.class);

    /**
     * 生成一行数据
     * @return 一行数据
     */
    public abstract String getLine();

    /**
     * 以文件的形式获取数据
     * @param targetSize 目标文件大小
     */
    public void getAsFile(String path, long targetSize) {
        LOG.error("正在生成输入文件...");
        long offset = 0;
        Path outputPath = Paths.get(path);
        try {
            Files.createDirectories(outputPath.getParent());
        } catch (IOException e) {
            LOG.error("父文件夹无法创建!");
            throw new RuntimeException(e);
        }
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(outputPath)))) {
            while (offset < targetSize) {
                String line = getLine();
                writer.write(line);
                writer.write('\n');
                offset += line.getBytes().length + 1;
            }
        } catch (IOException e) {
            LOG.error("无法写入文件！");
            throw new RuntimeException(e);
        }
    }

    /**
     * 以流的形式获取数据
     * @return 数据流
     */
    public Stream<String> getAsStream() {
        return Stream.generate(this::getLine);
    }
}
